from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.hashers import make_password, check_password
from django.core.urlresolvers import reverse
import time,os
from .. import models
from web.settings import BASE_DIR
from django.core.paginator import Paginator
from django.db.models import Q
from . viewsIndex import upload
# Create your views here.
# 首页
# def index(request):
#     return render(request,'myadmin/index.html')
# 添加数据
def useradd(request):
    if request.method=='GET':
        return render(request,'myadmin/add.html')
    elif request.method=='POST':
        try:
            data=request.POST.dict()
            data.pop('csrfmiddlewaretoken')
            myfile=request.FILES.get("pic_url",None)
            if myfile:
                pic=upload(myfile)
                data['pic_url']=pic
            else:
                data['pic_url']='/static/pics/user.png'
            ob=models.Users(**data)
            print(data,'1')
            ob.save()
            # return HttpResponse('hhhhhhhhhhhhhhhhhhh')
            return HttpResponse('<script>alert("添加成功");location.href="'+reverse('myadmin_user_list')+'"</script>')
        except:
            return HttpResponse('<script>alert("添加失败");location.href=""</script>')

# 查询所有用户
def userlist(request):
    data=models.Users.objects.all().exclude(status=2)
    keywords = request.GET.get('keywords')
    types = request.GET.get('types')
    # 判断有没有条件查询
    if types:
        try:
            if types == 'all':
                # select * from users where username like %keywords% or email like %keywords%
                # models.Users.objects.filter(username__contains('123'),email__contains('123'))
                # data = models.Users.objects.filter(username__contains('123'))
                # data.filter(,email__contains('123'))
                data=data.filter(Q(username__contains=keywords)|Q(phone__contains=keywords))
            elif types =='sex':
                key={'男':1,'女':0}
                data=data.filter(sex__contains=key[keywords])
            elif types =='status':
                key={'正常':0,'注销':2}
                data=data.filter(status__contains=key[keywords])
            else:
                t = {types+'__contains':keywords}
                data = data.filter(**t)
        except:
            pass

     # 数据分页
    # 实例化分页类 第一个参数所有的数据集合 每页要显示的条数
    p = Paginator(data,10)
    # 统计所有的数据
    # sum_data=p.count
    # 获取可以分多少页 
    page_num=p.num_pages
    # 分页的范围 range(1,)
    pagenums = p.page_range
    
    # 接受页码
    pg = int(request.GET.get('p',1))
    # 判断当前页码不能小于1
    if pg<1:
        pg=1
    if pg>page_num:
        pg=page_num
    # 获取第几页的数据
    pagedata = p.page(pg)
    # 限制边界 如果当前页码小于或=3 只区前五条数据
    # 
    if pg <= 3:
        pag_list=pagenums[:5]
    elif pg+2> page_num:
         pag_list=pagenums[-5:]
    else:
        pag_list=pagenums[pg-3:pg+2]
    print(pag_list)


    return render(request,'myadmin/userlist.html',{'info':pagedata,'pagenums':pag_list,'pg':pg})
# 删除数据
def dell(request,uid):
    ob=models.Users.objects.get(id=uid)
    ob.status=2
    ob.save()
    return HttpResponse('<script>alert("删除成功");location.href="'+reverse('myadmin_user_list')+'"</script>')

#修改数据
def re(request,uid):
    ob=models.Users.objects.get(id=uid)
    if request.method=='GET':
        return render(request,'myadmin/re.html',{'info':ob})
    elif request.method=='POST':
        ob.username=request.POST.get('username')
        ob.password=request.POST.get('password')
        ob.phone=request.POST.get('phone')
        ob.sex=request.POST.get('sex')
        ob.age=request.POST.get('age')
        ob.email=request.POST.get('email')
        
        if request.FILES.get('pic_url'):
            if ob.pic_url != '/static/pics/user.png':
                os.remove(BASE_DIR+ob.pic_url)
            myfile=request.FILES.get('pic_url')
            ob.pic_url=upload(myfile)
        ob.save()
        return HttpResponse('<script>alert("修改成功");location.href="'+reverse('myadmin_user_list')+'"</script>')





# def upload(myfile):
#     #执行图片的上传
#     filename = str(time.time())+"."+myfile.name.split('.').pop()
#     destination = open("./static/pics/"+filename,"wb+")
#     for chunk in myfile.chunks():      # 分块写入文件  
#         destination.write(chunk)  
#     destination.close()
#     # /static/picsn/图片
#     return '/static/pics/'+filename